package com.opennetexam.manager.common;

import com.opennetexam.manager.enums.OperationResultType;
import com.opennetexam.manager.utils.EncrptUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author 奶茶
 * Created on 2017/11/10.
 */
@Controller
@RequestMapping(value = "/Utils")
public class UtilController {

    private static Logger logger = Logger.getLogger(UtilController.class);

    @Value("${key}")
    private String key;

    /**
     * 获取系统时间
     */
    @RequestMapping(value = "/GetTime",method = RequestMethod.POST)
    public void getTime(HttpServletResponse response){
        long l = System.currentTimeMillis();
        String date = "/Date("+l+")/";
        CommonFunction.responseWrite(response,date);
    }

    @Autowired
    public ResourceLoader resourceLoader;

    /**
     * 路由响应
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/Html/{path1:\\w+}-{path2:\\w+}",method = RequestMethod.GET)
    @ResponseBody
    public void html(@PathVariable("path1") String dir, @PathVariable("path2")String name, HttpServletResponse response) throws IOException{

        String filePath = String.format("/static/App/views/%s/%s.html",dir,name);
        Resource resource = new ClassPathResource(filePath);
        InputStream inputStream = resource.getInputStream();
        response.setContentType("text/html; charset=utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputStream.read(buffer)) != -1) {
            //写到输出流(out)中
            outputStream.write(buffer, 0, b);
        }
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }

    /**
     * 加密
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/Encrypt/",method = RequestMethod.POST)
    public void desEncrypt(@RequestBody Map<String,Object> requestBody, HttpServletResponse response){
        OperationResult operationResult = new OperationResult();
        String encryptStr = "";
        String message = "生成请求参数成功！";
        try {
            String parameter = (String) requestBody.get("str");
            logger.info("加密参数："+parameter);
            encryptStr = EncrptUtil.encryptAsDoNet(parameter, key);
            logger.info("加密结果："+encryptStr);
            encryptStr = URLEncoder.encode(encryptStr,"UTF-8");
            logger.info("转译结果："+encryptStr);
            operationResult.setResultType(OperationResultType.Success);
        } catch (Exception e) {
            e.printStackTrace();
            operationResult.setResultType(OperationResultType.NoChanged);
            message = e.getMessage();
        }
        operationResult.setAppendData(encryptStr);
        operationResult.setMessage(message);
        CommonFunction.responseWrite(response,operationResult);
    }

    /**
     * 解密
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/Decrypt",method = RequestMethod.POST)
    public void desDecrypt(@RequestBody Map<String,Object> requestBody,HttpServletResponse response){
        OperationResult operationResult = new OperationResult();
        String decryptStr = "";
        String message = "解析请求参数成功！";
        try {
            String parameter = (String) requestBody.get("str");
            //parameter = URLDecoder.decode(parameter,"UTF-8");
            decryptStr = EncrptUtil.decryptDoNet(parameter, key);
            logger.info("解密请求参数："+parameter);
            logger.info("解密结果："+decryptStr);
            operationResult.setResultType(OperationResultType.Success);
        } catch (Exception e) {
            e.printStackTrace();
            operationResult.setResultType(OperationResultType.NoChanged);
            message = e.getMessage();
        }
        operationResult.setAppendData(decryptStr);
        operationResult.setMessage(message);
        CommonFunction.responseWrite(response,operationResult);
    }
}
